package com.lry.web.video.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.lry.web.information.entity.Information;
import com.lry.web.information.service.InformationService;
import com.lry.web.message.service.MessageService;
import com.lry.web.rests.LoadingCacheService;
import com.lry.web.util.IPUtil;
import com.lry.web.util.Result;
import com.lry.web.util.ResultUtil;
import com.lry.web.util.TransformUtil;
import com.lry.web.video.entity.Video;
import com.lry.web.video.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/video")
public class VideoController {
    @Autowired
    VideoService videoService;
    @Autowired
    MessageService messageService;
    @Autowired
    InformationService informationService;
    @Autowired
    LoadingCacheService loadingCacheService;
    //用于缓存key，防止重复采集
    public static List<String> keys = new ArrayList<>();
    public static Integer istatus = 1;

    //搜索视频名
    @RequestMapping(value = {"/search/{option}/{key}/{from}/{size}","/search/{option}/{key}/{from}","/search/{option}/{key}"})
    @ResponseBody
    public Result videoSearch(HttpServletRequest request, @PathVariable(value = "option") String option, @PathVariable(value = "key") String key, @PathVariable(value = "from",required=false) Integer from, @PathVariable(value = "size",required=false) Integer size) throws IOException {
        String ipAddr = IPUtil.getIpAddr(request);
        try {
            RateLimiter limiter = loadingCacheService.getRateLimiter(ipAddr);
            if(limiter.tryAcquire()){
                if(from==null){
                    from = 1;
                }
                if(size == null){
                    size = 10;
                }
                if(size>100){
                    size = 100;
                }
                Map<String,Object> videosMap= videoService.getVideos(key, TransformUtil.camelToUnderline(option),from,size);
                List<Video> videos =(List<Video>) videosMap.get("data");
                long count = (long) videosMap.get("count");
                if(videos.size()==0){
                    //如果视频不存在，加入采集队列
                    if(!keys.contains(key) && istatus==0) {
                        spiderVideo(key);
                        keys.add(key);
                        return ResultUtil.error(1,"没有查询到相关数据！已加入采集队列，请过段时间再来。");
                    }
                    return ResultUtil.error(1,"没有查询到相关数据！");
                }
                Map<String, Object> listMap = new HashMap<String, Object>();
                listMap.put("count",count);
                listMap.put("size",size);
                listMap.put("from",from);
                listMap.put("data",videos);
                return ResultUtil.success(listMap);

            }else {
                return ResultUtil.error(2,"请求过于频繁");
            }
        } catch (ExecutionException e) {
            return ResultUtil.error(1,"系统错误");
        }


    }

    //删除指定视频
    @RequestMapping("/deleteByVId/{videoId}")
    @ResponseBody
    public Result deleteByVId(@PathVariable(value = "videoId")String videoId) throws Exception {
        int i = videoService.deleteByVideoId(videoId);
        if(i!=0){
            return ResultUtil.success();
        }else {
            return ResultUtil.error(1,"失败");
        }
    }

    //删除指定源站全部视频,效率非常低,不推荐使用
//    @RequestMapping("/deleteByVVId/{vVId}")
//    @ResponseBody
//    public Result deleteVideoByVVId(@PathVariable(value = "vVId")String vVId) throws Exception {
//        int i = videoService.deleteByVVId(vVId);
//        if(i!=0){
//            return ResultUtil.success();
//        }else {
//            return ResultUtil.error(1,"删除失败");
//        }
//    }
    //修改自动采集状态
    @RequestMapping("/updateGather")
    @ResponseBody
    public Result updateGather() {
        if(istatus == 0){
            istatus = 1;
        }else{
            istatus = 0;
        }
        return ResultUtil.success();
    }
    //发起爬取视频请求
    @RequestMapping("/spider/{title}")
    @ResponseBody
    public Result spiderVideo(@PathVariable(value = "title")String title){
        String uuid =  UUID.randomUUID().toString();
        try {
            informationService.setInformation(new Information(uuid,"视频","采集关键词："+title,"待定",new Date(),null));
            int i =videoService.spiderVideo(title+","+uuid);
            if(i==2){
                return ResultUtil.error(2,"系统错误,MQ接收失败");
            }else if(i==3){
                return ResultUtil.error(2,"系统错误,采集端接收失败");
            }
        }catch (Exception e){
            return ResultUtil.error(2,"系统错误");
        }
        return ResultUtil.success();
    }
    @RequestMapping("/selectNum")
    @ResponseBody
    public Result selectVideoNum(){
        return ResultUtil.success(videoService.selectNum());

    }

    //清除采集缓存
    @RequestMapping("/deleteKeysCache")
    @ResponseBody
    public Result delKeysCache(){
        keys.clear();
        return ResultUtil.success();
    }



}
